package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytedance.ads.model.FileVideoGetV2ResponseData;
import com.bytedance.ads.model.FileVideoGetV2ResponseDataListInner;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.oce.domain.OceMaterial;
import org.dromara.oce.domain.bo.OceMaterialBo;
import org.dromara.oce.domain.qo.GetVideoListQo;
import org.dromara.oce.domain.qo.OceMaterialQo;
import org.dromara.oce.domain.vo.OceMaterialVo;
import org.dromara.oce.mapper.OceMaterialMapper;
import org.dromara.oce.service.OceMaterialService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 素材Service业务层处理
 *
 * @author dsbb
 * @date 2025-06-05
 */
@RequiredArgsConstructor
@Service
public class OceMaterialServiceImpl extends ServiceImpl<OceMaterialMapper, OceMaterial> implements OceMaterialService {

    private final OceMaterialMapper baseMapper;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;

    /**
     * 查询素材
     *
     * @param materialId 主键
     * @return 素材
     */
    @Override
    public OceMaterialVo queryById(Long materialId) {
        return baseMapper.selectVoById(materialId);
    }

    /**
     * 分页查询素材列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 素材分页列表
     */
    @Override
    public TableDataInfo<OceMaterialVo> queryPageList(OceMaterialQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceMaterial> lqw = buildQueryWrapper(qo);
        Page<OceMaterialVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询素材列表 消耗
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 素材分页列表
     */
    @Override
    public TableDataInfo<OceMaterialVo> queryPageListCost(OceMaterialQo qo, PageQuery pageQuery) {
        qo.setDate(DateUtil.today());
        Page<OceMaterialVo> result = baseMapper.selectVoPageCost(pageQuery.build(), qo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的素材列表
     *
     * @param qo 查询条件
     * @return 素材列表
     */
    @Override
    public List<OceMaterialVo> queryList(OceMaterialQo qo) {
        LambdaQueryWrapper<OceMaterial> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceMaterial> buildQueryWrapper(OceMaterialQo qo) {
        LambdaQueryWrapper<OceMaterial> lqw = Wrappers.lambdaQuery();
        lqw.like(!ObjectUtils.isEmpty(qo.getMaterialId()),OceMaterial::getMaterialId,qo.getMaterialId());
        lqw.ge(!ObjectUtils.isEmpty(qo.getStartTime()),OceMaterial::getCreateTime,qo.getStartTime());
        lqw.le(!ObjectUtils.isEmpty(qo.getEndTime()),OceMaterial::getCreateTime,qo.getEndTime());
//        lqw.eq(!ObjectUtils.isEmpty(qo.getIsFirstPublishMaterial()),OceMaterial::getMaterialId,qo.getIsFirstPublishMaterial());
//        lqw.eq(!ObjectUtils.isEmpty(qo.getIsAdHighQualityMaterial()),OceMaterial::getIsAdHighQualityMaterial,qo.getIsAdHighQualityMaterial());
        lqw.like(!ObjectUtils.isEmpty(qo.getFilename()),OceMaterial::getFilename,qo.getFilename());
        lqw.eq(!ObjectUtils.isEmpty(qo.getAdvertiserId()),OceMaterial::getAdvertiserId,qo.getAdvertiserId());
        lqw.eq(!ObjectUtils.isEmpty(qo.getAccountId()),OceMaterial::getAccountId,qo.getAccountId());
        lqw.orderByDesc(OceMaterial::getMaterialId);
        return lqw;
    }

    /**
     * 新增素材
     *
     * @param bo 素材
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceMaterialBo bo) {
        OceMaterial add = MapstructUtils.convert(bo, OceMaterial.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMaterialId(add.getMaterialId());
        }
        return flag;
    }

    /**
     * 修改素材
     *
     * @param bo 素材
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceMaterialBo bo) {
        OceMaterial update = MapstructUtils.convert(bo, OceMaterial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceMaterial entity) {
    }

    /**
     * 校验并批量删除素材信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void syncMeterial(Long accountId, Long advertiserId,String startTime, String endTime) {
        //查询广告主下的所有素材
        LambdaQueryWrapper<OceMaterial> lambdaQuery = Wrappers.lambdaQuery();
//        lambdaQuery.ge(!ObjectUtils.isEmpty(startTime),OceMaterial::getCreateTime,startTime);
//        lambdaQuery.le(!ObjectUtils.isEmpty(endTime),OceMaterial::getCreateTime,endTime+" 23:59:59");
        lambdaQuery.eq(!ObjectUtils.isEmpty(advertiserId),OceMaterial::getAdvertiserId,advertiserId);
        lambdaQuery.eq(!ObjectUtils.isEmpty(accountId),OceMaterial::getAccountId,accountId);
        this.remove(lambdaQuery);

        GetVideoListQo qo = new GetVideoListQo();
        qo.setAccountId(accountId);
        qo.setAdvertiserId(advertiserId);
        qo.setStartTime(startTime);
        qo.setEndTime(endTime);
        qo.setPageSize(100L);
        qo.setPageNum(1L);
        Long page = 1L;
        Long totalPage = 0L;
        List<OceMaterial> list = new ArrayList<>();
        do {
            FileVideoGetV2ResponseData pageData = oceanEngineThirdRemoteService.getVideoList(qo);
            totalPage = pageData.getPageInfo().getTotalPage();

            for (FileVideoGetV2ResponseDataListInner dataListInner : pageData.getList()) {
                OceMaterial oceMaterial = BeanUtil.copyProperties(dataListInner, OceMaterial.class);
                oceMaterial.setAdvertiserId(advertiserId);
                oceMaterial.setAccountId(accountId);
                list.add(oceMaterial);
            }

            if (list.size() >= 500) {
                this.baseMapper.insertBatch(list);
                list = new ArrayList<>();
            }

            page = page + 1;
            qo.setPageNum(page);
        } while (page <= totalPage);

        if (list.size() > 0) {
            this.baseMapper.insertBatch(list);
        }

    }
}
